Page({
  data: {
    notes: [],
    searchText: '',
    filteredNotes: [],
    isSearching: false
  },

  onLoad() {
    this.loadNotes();
  },

  onShow() {
    this.loadNotes();
  },

  loadNotes() {
    const notes = wx.getStorageSync('notes') || [];
    this.setData({ 
      notes,
      filteredNotes: notes 
    });
  },

  // 搜索输入处理
  onSearchInput(e) {
    const searchText = e.detail.value;
    this.setData({ searchText });
    this.filterNotes(searchText);
  },

  // 过滤笔记
  filterNotes(searchText) {
    if (!searchText.trim()) {
      this.setData({
        filteredNotes: this.data.notes,
        isSearching: false
      });
      return;
    }

    const filteredNotes = this.data.notes.filter(note => {
      const titleMatch = note.title && note.title.toLowerCase().includes(searchText.toLowerCase());
      const contentMatch = note.content && note.content.toLowerCase().includes(searchText.toLowerCase());
      const tagMatch = note.tag && note.tag.toLowerCase().includes(searchText.toLowerCase());
      
      return titleMatch || contentMatch || tagMatch;
    });

    this.setData({
      filteredNotes,
      isSearching: true
    });
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchText: '',
      filteredNotes: this.data.notes,
      isSearching: false
    });
  },

  addNote() {
    wx.navigateTo({
      url: '/pages/edit/edit'
    });
  },

  editNote(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/edit/edit?id=${id}`
    });
  }
});